package com.thinkgem.jeesite.modules.oa.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.act.service.ActTaskService;
import com.thinkgem.jeesite.modules.oa.dao.FlowDao;
import com.thinkgem.jeesite.modules.oa.dao.TargetHospitalDao;
import com.thinkgem.jeesite.modules.oa.dao.TravelApplicationDao;
import com.thinkgem.jeesite.modules.oa.entity.FlowData;
import com.thinkgem.jeesite.modules.oa.entity.PersonSigns;
import com.thinkgem.jeesite.modules.oa.entity.TargetHospital;
import com.thinkgem.jeesite.modules.oa.entity.TravelApplication;
import com.thinkgem.jeesite.modules.oa.units.OConvertUtils;
import com.thinkgem.jeesite.modules.sys.dao.OfficeDao;
import com.thinkgem.jeesite.modules.sys.dao.UserDao;
import com.thinkgem.jeesite.modules.sys.dao.AddDictDao;
import com.thinkgem.jeesite.modules.sys.entity.AddDict;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.entity.Role;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.modules.table.dao.OaPersonDefineTableColumnDao;
import com.thinkgem.jeesite.modules.table.dao.OaPersonDefineTableDao;
import com.thinkgem.jeesite.modules.table.entity.OaPersonDefineTable;
import com.thinkgem.jeesite.modules.table.entity.OaPersonDefineTableColumn;
import org.activiti.engine.HistoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.task.Task;
import org.aspectj.weaver.ast.Instanceof;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.authentication.UserServiceBeanDefinitionParser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.FileHandler;

/**
 * 审批Service
 *
 * @author thinkgem
 * @version 2014-05-16
 */
@Service
@Transactional(readOnly = true)
public class FlowService extends CrudService<FlowDao, FlowData> {

    @Autowired
    private ActTaskService actTaskService;
    @Autowired
    private TaskService taskService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private OaPersonDefineTableDao oaPersonDefineTableDao;
    @Autowired
    private OaPersonDefineTableColumnDao oaPersonDefineTableColumnDao;

    @Autowired
    private UserDao userDao;
    @Autowired
    private OfficeDao officeDao;

    @Autowired
    private AddDictDao addDictDao;
    @Autowired
    private TargetHospitalDao targetHospitalDao;

    @Autowired
    private TravelApplicationDao travelApplicationDao;



    /**
     * 保存附件路径
     *
     * @param file
     * @param name
     * @param signName
     * @param request
     * @throws java.io.IOException
     */
    @Transactional(readOnly = false)
    public String saveContractFile(MultipartFile file, String name, String signName, String id, HttpServletRequest request) throws IOException {
        InputStream inputStream = file.getInputStream();
        String filePath = null;
        String realPath = request.getSession().getServletContext().getRealPath("/static" + File.separator + "userfiles");
        String oldName = null;
        oldName = file.getOriginalFilename();
        if (StringUtils.isNotEmpty(oldName)) {
            String filename = oldName.substring(oldName.lastIndexOf("."));
            filename = UserUtils.getUser().getLoginName() + "_" + System.currentTimeMillis() + filename;
            realPath = realPath + File.separator + "attachment";
            File targetFile = new File(realPath);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            File desFile = new File(realPath + File.separator + filename);
            if (!desFile.exists()) {
                desFile.createNewFile();
            }
            filePath = desFile.getPath();
            FileOutputStream fileOutputStream = new FileOutputStream(desFile);
            String s = filePath.replaceAll("\\\\", "\\/");
            byte[] bytes = new byte[1024];
            while (!(inputStream.read(bytes) == -1)) {
                fileOutputStream.write(bytes);
            }
            fileOutputStream.flush();
            fileOutputStream.close();
            inputStream.close();
            filePath = filePath.substring(filePath.lastIndexOf("static") - 1);
        }

        //文件保存成功
        return oldName + "," + filePath;
    }


    /**
     * 表单添加
     *
     * @param flowData
     * @throws Exception
     */
    public String insertTable(FlowData flowData) {
        String tableName = flowData.getTableName();
        Map<String, Object> data = flowData.getDatas();
        String userId = "";
        String createById = "";
        String createName = "";
        OaPersonDefineTable defineTable = oaPersonDefineTableDao.findByTableName(tableName, null);
        if (defineTable != null && data != null && StringUtils.isNotBlank(tableName)) {
            List<OaPersonDefineTableColumn> columns = oaPersonDefineTableColumnDao.findColumnListByTableId(defineTable.getId());
            dataAdapter(columns, data);
            String comma = "";
            String dept = "";
            StringBuffer insertKey = new StringBuffer();
            StringBuffer insertValue = new StringBuffer();
            for (Map.Entry<String, Object> entry : data.entrySet()) {
                // 判断key是否为表配置的属性
                if (isContainsFieled(columns, entry.getKey())) {
                    if (!entry.getKey().equalsIgnoreCase("BZ")) {
                        insertKey.append(comma + entry.getKey());
                    }
                    if (entry.getValue() != null && entry.getValue().toString().length() > 0) {

                        if (entry.getKey().equalsIgnoreCase("CCR") || entry.getKey().equalsIgnoreCase("SQR")) {
                            userId = entry.getValue().toString();
                            User user1 = new User();
                            user1.setName(userId.replace("'", ""));
                            User create = userDao.findByName(user1);
                            createById = create.getId();
                            createName = create.getLoginName();
                        }


                        if (entry.getKey().equalsIgnoreCase("BH")) {
                            String sql = "select max(BH) from " + defineTable.getTableName();
                            String max = oaPersonDefineTableDao.getMax(sql);
                            if (StringUtils.isNotEmpty(max)) {
                                String sub = max.substring(1, max.length());
                                int orderValue = Integer.parseInt(sub);
                                orderValue++;
                                int n = orderValue;
                                NumberFormat formatter = NumberFormat.getNumberInstance();
                                formatter.setMinimumIntegerDigits(6);
                                formatter.setGroupingUsed(false);
                                String s = formatter.format(n);
                                String now = "A" + s;
                                insertValue.append(comma + "'" + now + "'");
                            } else {
                                String ret = "A000001";
                                insertValue.append(comma + "'" + ret + "'");
                            }
                        } else {
                            if (entry.getKey().equalsIgnoreCase("CCR") || entry.getKey().equalsIgnoreCase("SQR")) {
                                dept = updateDept(entry.getKey(), entry.getValue().toString());
                            }
                            if (entry.getKey().equalsIgnoreCase("BM")) {
                                if (StringUtils.isNotEmpty(dept)) {
                                    insertValue.append(comma + "'" + dept + "'");
                                } else {
                                    if (!entry.getKey().equalsIgnoreCase("BZ")) {
                                        insertValue.append(comma + entry.getValue());
                                    }
                                }
                            } else {
                                if (entry.getKey().equalsIgnoreCase("FJLJ")) {
                                    String ls = entry.getValue().toString().replace("\\", "\\\\");
                                    insertValue.append(comma + ls);
                                } else {
                                    if (!entry.getKey().equalsIgnoreCase("BZ")) {
                                        insertValue.append(comma + entry.getValue());
                                    }
                                }
                            }


                        }
                    } else {
                        if (entry.getKey().equalsIgnoreCase("BH")) {
                            String sql = "select max(BH) from " + defineTable.getTableName();
                            String max = oaPersonDefineTableDao.getMax(sql);
                            if (StringUtils.isNotEmpty(max)) {
                                String sub = max.substring(1, max.length());
                                int orderValue = Integer.parseInt(sub);
                                orderValue++;
                                int n = orderValue;
                                NumberFormat formatter = NumberFormat.getNumberInstance();
                                formatter.setMinimumIntegerDigits(6);
                                formatter.setGroupingUsed(false);
                                String s = formatter.format(n);
                                String now = "A" + s;
                                insertValue.append(comma + "'" + now + "'");
                            } else {
                                String ret = "A000001";
                                insertValue.append(comma + "'" + ret + "'");
                            }
                        } else {
                            insertValue.append(comma + "null");
                        }

                    }
                    comma = ", ";
                }
             }
            insertKey.append(",id,create_date,update_by,update_date,remarks,del_flag,proc_def_id");
            insertValue.append(comma + handleSqlValue(flowData.getId(), "varchar"))
                    .append(comma + handleSqlValue(DateUtils.formatDateTime(flowData.getCreateDate()), "date"))
                    .append(comma + handleSqlValue(flowData.getUpdateBy(), "varchar"))
                    .append(comma + handleSqlValue(DateUtils.formatDateTime(flowData.getUpdateDate()), "date"))
                    .append(comma + handleSqlValue(flowData.getRemarks(), "varchar"))
                    .append(comma + handleSqlValue(flowData.getDelFlag(), "varchar"))
                    .append(comma + handleSqlValue(flowData.getAct().getProcDefId(), "varchar"));
            if (StringUtils.isNotEmpty(createById)) {
                if (StringUtils.equalsIgnoreCase("zhaowj", createName) || StringUtils.equalsIgnoreCase("cheng", createName)) {
                    insertKey.append(",create_by");
                    insertValue.append(comma + handleSqlValue(flowData.getCreateBy(), "varchar"));
                } else {
                    insertKey.append(",create_by");
                    insertValue.append(comma + handleSqlValue(createById, "varchar"));
                }
            } else {
                insertKey.append(",create_by");
                insertValue.append(comma + handleSqlValue(flowData.getCreateBy(), "varchar"));
            }
            String sql = "INSERT INTO " + tableName + " (" + insertKey + ") VALUES (" + insertValue + ")";
            oaPersonDefineTableDao.executeSql(sql);
        }
        return userId;
    }


    public String updateDept(String key, String value) {
        User user = new User();
        user.setName(value.replace("\'", ""));
        user = userDao.getByName(user);
        Office office = officeDao.get(user.getOffice().getId());
        return office.getName();
    }

    /**
     * 表单添加
     *
     * @param flowData
     * @throws Exception
     */
    public void updateTable(FlowData flowData) {
        String tableName = flowData.getTableName();
        Map<String, Object> data = flowData.getDatas();
        OaPersonDefineTable defineTable = oaPersonDefineTableDao.findByTableName(tableName, null);
        if (defineTable != null && data != null && StringUtils.isNotBlank(tableName) && flowData.getAct().getTaskDefKey().startsWith("modify")) {
            List<OaPersonDefineTableColumn> columns = oaPersonDefineTableColumnDao.findColumnListByTableId(defineTable.getId());
            dataAdapter(columns, data);
            String comma = "";
            StringBuffer updateValue = new StringBuffer();
            for (Map.Entry<String, Object> entry : data.entrySet()) {
                // 判断key是否为表配置的属性
                if (isContainsFieled(columns, entry.getKey())) {
                    if (!(entry.getKey().equalsIgnoreCase("FJLJ") || entry.getKey().equalsIgnoreCase("FJMC"))) {
                        updateValue.append(comma + entry.getKey() + "=");
                    }
                    if (entry.getValue() != null && entry.getValue().toString().length() > 0) {
                        if (entry.getKey().equalsIgnoreCase("BH")) {
                            String sql = "select max(BH) from " + defineTable.getTableName();
                            String max = oaPersonDefineTableDao.getMax(sql);
                            if (StringUtils.isNotEmpty(max)) {
                                String sub = max.substring(1, max.length());
                                int orderValue = Integer.parseInt(sub);
//                                orderValue++;
                                int n = orderValue;
                                NumberFormat formatter = NumberFormat.getNumberInstance();
                                formatter.setMinimumIntegerDigits(6);
                                formatter.setGroupingUsed(false);
                                String s = formatter.format(n);
                                String now = "A" + s;
                                updateValue.append("'" + now + "'");
                                comma = ", ";
                            } else {
                                String ret = "A000001";
                                updateValue.append("'" + ret + "'");
                                comma = ", ";
                            }
                        } else {
                            if (entry.getKey().equalsIgnoreCase("FJMC") || entry.getKey().equalsIgnoreCase("FJLJ")) {
                                if (entry.getKey().equalsIgnoreCase("FJLJ")) {
                                    String lj = entry.getValue().toString().replace("\\", "\\\\");
                                    updateValue.append(comma + entry.getKey() + "=" + lj);
                                    comma = ", ";
                                } else {
                                    updateValue.append(comma + entry.getKey() + "=" + entry.getValue());
                                    comma = ", ";
                                }
                            } else {
                                updateValue.append(entry.getValue());
                                comma = ", ";
                            }
                        }

                    } else {
                        if (entry.getKey().equalsIgnoreCase("BH")) {
                            String sql = "select max(BH) from " + defineTable.getTableName();
                            String max = oaPersonDefineTableDao.getMax(sql);
                            if (StringUtils.isNotEmpty(max)) {
                                String sub = max.substring(1, max.length());
                                int orderValue = Integer.parseInt(sub);
                                orderValue++;
                                int n = orderValue;
                                NumberFormat formatter = NumberFormat.getNumberInstance();
                                formatter.setMinimumIntegerDigits(6);
                                formatter.setGroupingUsed(false);
                                String s = formatter.format(n);
                                String now = "A" + s;
                                updateValue.append("'" + now + "'");
                                comma = ", ";
                            } else {
                                String ret = "A000001";
                                updateValue.append("'" + ret + "'");
                                comma = ", ";
                            }
                        } else {
                            if (!(entry.getKey().equalsIgnoreCase("FJLJ") || entry.getKey().equalsIgnoreCase("FJMC"))) {
                                updateValue.append("null");
                                comma = ", ";
                            }

                        }
                    }
                }
            }
            updateValue.append(comma + "update_by=" + handleSqlValue(flowData.getUpdateBy(), "varchar"))
                    .append(",update_date=" + handleSqlValue(flowData.getUpdateDate() == null ? null : DateUtils.formatDateTime(flowData.getUpdateDate()), "date"));
            String sql = "UPDATE " + tableName + " SET " + updateValue + " where id='" + flowData.getId() + "'";
            oaPersonDefineTableDao.executeSql(sql);
        } else if (flowData.getAct().getTaskDefKey().startsWith("edit")) {
            OaPersonDefineTable defineTable1 = oaPersonDefineTableDao.findByTableName(tableName, null);
            List<OaPersonDefineTableColumn> columns = oaPersonDefineTableColumnDao.findColumnListByTableId(defineTable1.getId());
            dataAdapter(columns, data);
            String comma = "";
            StringBuffer updateValue = new StringBuffer();
            for (Map.Entry<String, Object> entry : data.entrySet()) {
                // 判断key是否为表配置的属性
                if (isContainsFieled(columns, entry.getKey())) {
                    updateValue.append(comma + entry.getKey() + "=");
                    if (entry.getValue() != null && entry.getValue().toString().length() > 0) {
                        updateValue.append(entry.getValue());
                    } else {
                        updateValue.append("null");
                    }
                    comma = ", ";
                }
            }
            updateValue.append(comma + "update_by=" + handleSqlValue(flowData.getUpdateBy(), "varchar"))
                    .append(",update_date=" + handleSqlValue(flowData.getUpdateDate() == null ? null : DateUtils.formatDateTime(flowData.getUpdateDate()), "date"));
            String sql = "UPDATE " + tableName + " SET " + updateValue + " where id='" + flowData.getId() + "'";
            oaPersonDefineTableDao.executeSql(sql);
        }
    }

    public List<Map<String, Object>> getFlowInfo(Map<String, String> paramMap) {
        String sql = getSelectSql(paramMap);
        if (StringUtils.isNotBlank(sql)) {
            return oaPersonDefineTableDao.getFlowInfo(sql);
        }
        return Lists.newArrayList();
    }

    public Page<Map<String, Object>> getPageFlowInfo(Page<FlowData> page, Map<String, String> paramMap) {
        FlowData flow = new FlowData();
        flow.setPage(page);
        flow.setSql(getSelectSql(paramMap));
        List<Map<String, Object>> list = oaPersonDefineTableDao.getFlowInfo(flow);
        Page<Map<String, Object>> result = new Page<>(page.getPageNo(), page.getPageSize(), page.getCount());
        result.setList(list);
        return result;
    }

    public Map<String, Object> getOneInfo(Map<String, String> paramMap) {
        List<Map<String, Object>> infos = getFlowInfo(paramMap);
        if (infos != null && infos.size() > 0) {
            return infos.get(0);
        }
        return Maps.newHashMap();
    }


//
//	public Page<TestAudit> findPage(Page<TestAudit> page, TestAudit testAudit) {
//		testAudit.setPage(page);
//		page.setList(dao.findList(testAudit));
//		return page;
//	}
//
    /**
     * 查询当前登陆人发起的所有流程信息
     *
     * @return
     */
    @Transactional(readOnly = false)
    public List<OaPersonDefineTable> flowList() {
        //先查询出所有的流程表
        List<Map<String,Map<String,Object>>>list = new ArrayList<>();
        List<OaPersonDefineTable> oaPersonDefineTables = oaPersonDefineTableDao.findList(new OaPersonDefineTable());
        for(OaPersonDefineTable table : oaPersonDefineTables){
            String sql=null;
            String name=UserUtils.getUser().getRoleNames();
            if(StringUtils.equalsIgnoreCase("1",UserUtils.getUser().getId())){
                sql ="select proc_def_id  from " + table.getTableName() + " where del_flag = '0'";
            }else if(name.indexOf("双滦")!=-1 || name.indexOf("安平")!=-1){
                if(table.getTableName().indexOf("HP_")!=-1 || table.getTableName().indexOf("AP_")!=-1){
                    sql ="select proc_def_id  from " + table.getTableName() + " where del_flag = '0'";
                }
            }else if(name.indexOf("深圳")!=-1){
                if(table.getTableName().indexOf("SZ_")!=-1){
                    sql ="select proc_def_id  from " + table.getTableName() + " where del_flag = '0'";
                }
            }else{
                sql ="select proc_def_id  from " + table.getTableName() + " where del_flag = '0' and create_by = '" + UserUtils.getUser().getId() + "'";
            }
            if(StringUtils.isNotBlank(sql)){
                List<Map<String,Object>> sqls = oaPersonDefineTableDao.getFlowInfo(sql);
                if(sqls != null && sqls.size()>0){
                    Map<String,Map<String,Object>> maps = new HashMap<>();
                    maps.put(table.getTableComment(),sqls.get(0));
                    list.add(maps);
                }
            }else{
                continue;
            }

        }
        List<OaPersonDefineTable> stringList =new ArrayList<>();
        for(int i = 0;i<list.size();i++){
            Map<String,Map<String,Object>> map = list.get(i);
            for(Map.Entry<String,Map<String,Object>> entry : map.entrySet()){
                for(Map.Entry<String,Object> m : entry.getValue().entrySet()){
                    OaPersonDefineTable oaPersonDefineTable = new OaPersonDefineTable();
                    oaPersonDefineTable.setTableName(entry.getKey());
                    oaPersonDefineTable.setProcDefId(m.getValue().toString());
                    stringList.add(oaPersonDefineTable);
                }
            }
        }
        return stringList;
    }

    /**
     * 审核新增或编辑
     *
     * @param flowData
     */
    @Transactional(readOnly = false)
    public String saveFlow(FlowData flowData) {
        User user = UserUtils.getUser();
         String companyId = user.getCompany().getId();
        String DEL_FLAG_NORMAL="0";
        Map<String, Object> vars = handlerVar(flowData.getTableName(), flowData.getDatas());
        vars.put("PostGrade", user.getGrade());
        vars.put("parentId", user.getAcName());
        vars.put("dept", user.getAcDeptName());
        vars.put("leader", user.getLevel1Name());



        //行政专员
        AddDict ad1 = addDictDao.findByLabel("行政专员", companyId,DEL_FLAG_NORMAL);
        String hr=null;
        String hrName=null;
        if(ad1!=null){
            hr =ad1.getValue();
            hrName =ad1.getUserName();
            vars.put(hr, hrName);
        }
        //总经理
        AddDict ad2= addDictDao.findByLabel("总经理", companyId, DEL_FLAG_NORMAL);
        String manager=null;
        String managerName=null;
        if(ad2!=null){
            manager =ad2.getValue();
            managerName =ad2.getUserName();
            vars.put(manager, managerName);
        }
        //副总经理
        AddDict ad3 = addDictDao.findByLabel("副总经理", companyId,DEL_FLAG_NORMAL);
        String Fmanager=null;
        String FmanagerName=null;

        if(ad3!=null){
            Fmanager =ad3.getValue();
            FmanagerName =ad3.getUserName();
            vars.put(Fmanager, FmanagerName);
        }
        //出纳
        AddDict ad4 = addDictDao.findByLabel("出纳", companyId,DEL_FLAG_NORMAL);
        String assistant=null;
        String assistantName=null;
        if(ad4!=null){
            assistant =ad4.getValue();
            assistantName =ad4.getUserName();
            vars.put(assistant, assistantName);
        }


        //出纳
        AddDict slad18 = addDictDao.findByLabel("财务审核2", companyId,DEL_FLAG_NORMAL);
        String assistant2=null;
        String assistantName2=null;
        if(slad18!=null){
            assistant2 =slad18.getValue();
            assistantName2 =slad18.getUserName();
            vars.put(assistant2, assistantName2);
        }

        //ywglky
        AddDict slad38 = addDictDao.findByLabel("医务管理科员", companyId,DEL_FLAG_NORMAL);
        String ywglky=null;
        String ywglkyName=null;
        if(slad38!=null){
            ywglky =slad38.getValue();
            ywglkyName =slad38.getUserName();
            vars.put(ywglky, ywglkyName);
        }


        AddDict slad17= addDictDao.findByLabel("出纳2", companyId,DEL_FLAG_NORMAL);
        String cashier2=null;
        String cashierName2=null;
        if(slad17!=null){
            cashier2 =slad17.getValue();
            cashierName2 =slad17.getUserName();
            vars.put(cashier2, cashierName2);
        }

        AddDict slad1= addDictDao.findByLabel("医务管理组", companyId,DEL_FLAG_NORMAL);
        String ywglz=null;
        String ywglzName=null;
        if(slad1!=null){
            ywglz =slad1.getValue();
            ywglzName =slad1.getUserName();
            vars.put(ywglz, ywglzName);
        }



        AddDict slad2= addDictDao.findByLabel("执行院长", companyId,DEL_FLAG_NORMAL);
        String diroctor=null;
        String diroctorName=null;
        if(slad2!=null){
            diroctor =slad2.getValue();
            diroctorName =slad2.getUserName();
            vars.put(diroctor, diroctorName);
        }


        AddDict slad45= addDictDao.findByLabel("院长", companyId,DEL_FLAG_NORMAL);
        String yuanzhang=null;
        String yuanzhangName=null;
        if(slad45!=null){
            yuanzhang =slad45.getValue();
            yuanzhangName =slad45.getUserName();
            vars.put(yuanzhang, yuanzhangName);
        }


        AddDict slad3= addDictDao.findByLabel("信息科主管", companyId,DEL_FLAG_NORMAL);
        String xxkzg=null;
        String xxkzgName=null;
        if(slad3!=null){
            xxkzg =slad3.getValue();
            xxkzgName =slad3.getUserName();
            vars.put(xxkzg, xxkzgName);
        }



        AddDict slad4= addDictDao.findByLabel("物资管理主管", companyId,DEL_FLAG_NORMAL);
        String wzglzg=null;
        String wzglzgName=null;
        if(slad4!=null){
            wzglzg =slad4.getValue();
            wzglzgName =slad4.getUserName();
            vars.put(wzglzg, wzglzgName);
        }


        AddDict slad5= addDictDao.findByLabel("书记", companyId,DEL_FLAG_NORMAL);
        String shuji=null;
        String shujiName=null;
        if(slad5!=null){
            shuji =slad5.getValue();
            shujiName =slad5.getUserName();
            vars.put(shuji, shujiName);
        }



        AddDict slad6= addDictDao.findByLabel("医工科主管", companyId,DEL_FLAG_NORMAL);
        String ygkzg=null;
        String ygkzgName=null;
        if(slad6!=null){
            ygkzg =slad6.getValue();
            ygkzgName =slad6.getUserName();
            vars.put(ygkzg, ygkzgName);
        }

        AddDict slad7= addDictDao.findByLabel("护士长", companyId,DEL_FLAG_NORMAL);
        String hsz=null;
        String hszName=null;
        if(slad7!=null){
            hsz =slad7.getValue();
            hszName =slad7.getUserName();
            vars.put(hsz, hszName);
        }

        AddDict slad8= addDictDao.findByLabel("药剂科主任", companyId,DEL_FLAG_NORMAL);
        String drug=null;
        String drugName=null;
        if(slad8!=null){
            drug =slad8.getValue();
            drugName =slad8.getUserName();
            vars.put(drug, drugName);
        }

        AddDict slad9= addDictDao.findByLabel("物业服务部主管", companyId,DEL_FLAG_NORMAL);
        String wyfwbzg=null;
        String wyfwbzgName=null;
        if(slad9!=null){
            wyfwbzg =slad9.getValue();
            wyfwbzgName =slad9.getUserName();
            vars.put(wyfwbzg, wyfwbzgName);
        }
        AddDict slad10= addDictDao.findByLabel("物业经理", companyId,DEL_FLAG_NORMAL);
        String wyjl=null;
        String wyjlName=null;
        if(slad10!=null){
            wyjl =slad10.getValue();
            wyjlName =slad10.getUserName();
            vars.put(wyjl, wyjlName);
        }
        AddDict slad11= addDictDao.findByLabel("医护部部长", companyId,DEL_FLAG_NORMAL);
        String yhbbz=null;
        String yhbbzName=null;
        if(slad11!=null){
            yhbbz =slad11.getValue();
            yhbbzName =slad11.getUserName();
            vars.put(yhbbz, yhbbzName);
        }
        AddDict slad12= addDictDao.findByLabel("医务管理主管", companyId,DEL_FLAG_NORMAL);
        String ywglzg=null;
        String ywglzgName=null;
        if(slad12!=null){
            ywglzg =slad12.getValue();
            ywglzgName =slad12.getUserName();
            vars.put(ywglzg, ywglzgName);
        }

        //行政主管
        AddDict ad5 = addDictDao.findByLabel("行政主管", companyId,DEL_FLAG_NORMAL);
        String officer=null;
        String officerName=null;
        if(ad5!=null){
            officer =ad5.getValue();
            officerName =ad5.getUserName();
            vars.put(officer, officerName);
        }
        //人事专员
        AddDict ad6 = addDictDao.findByLabel("人事专员", companyId,DEL_FLAG_NORMAL);
        String rs=null;
        String rsName=null;
        if(ad6!=null){
            rs =ad6.getValue();
            rsName =ad6.getUserName();
            vars.put(rs,rsName );
        }


        AddDict slad24 = addDictDao.findByLabel("人事专员1", companyId,DEL_FLAG_NORMAL);
        String rszy1=null;
        String rszy1Name=null;
        if(slad24!=null){
            rszy1 =slad24.getValue();
            rszy1Name =slad24.getUserName();
            vars.put(rszy1,rszy1Name );
        }

        AddDict slad25 = addDictDao.findByLabel("人事专员2", companyId,DEL_FLAG_NORMAL);
        String rszy2=null;
        String rszy2Name=null;
        if(slad25!=null){
            rszy2 =slad25.getValue();
            rszy2Name =slad25.getUserName();
            vars.put(rszy2,rszy2Name );
        }
        //人事主管
        AddDict ad7 = addDictDao.findByLabel("人事主管", companyId,DEL_FLAG_NORMAL);
        String rsofficer=null;
        String rsofficerName=null;
        if(ad7!=null){
            rsofficer =ad7.getValue();
            rsofficerName =ad7.getUserName();
            vars.put(rsofficer, rsofficerName);
        }

        AddDict slad14 = addDictDao.findByLabel("人事主管2", companyId,DEL_FLAG_NORMAL);
        String rsofficer2=null;
        String rsofficerName2=null;
        if(slad14!=null){
            rsofficer2 =slad14.getValue();
            rsofficerName2 =slad14.getUserName();
            vars.put(rsofficer2, rsofficerName2);
        }
        //财务部经理
        AddDict ad8 = addDictDao.findByLabel("财务部经理", companyId, DEL_FLAG_NORMAL);
        String finalManager=null;
        String finalManagerName=null;
        if(ad8!=null){
            finalManager =ad8.getValue();
            finalManagerName =ad8.getUserName();
            vars.put(finalManager, finalManagerName);
        }

        //财务部经理
        AddDict slad15 = addDictDao.findByLabel("财务主管2", companyId, DEL_FLAG_NORMAL);
        String finalManager2=null;
        String finalManagerName2=null;
        if(slad15!=null){
            finalManager2 =slad15.getValue();
            finalManagerName2 =slad15.getUserName();
            vars.put(finalManager2, finalManagerName2);
        }



        //财务部经理
        AddDict slad30 = addDictDao.findByLabel("财务确认", companyId, DEL_FLAG_NORMAL);
        String cwqr=null;
        String cwqrrName2=null;
        if(slad30!=null){
            cwqr =slad30.getValue();
            cwqrrName2 =slad30.getUserName();
            vars.put(cwqr, cwqrrName2);
        }
        //抄送会计打印
        AddDict ad9= addDictDao.findByLabel("抄送会计打印", companyId,DEL_FLAG_NORMAL);
        String print=null;
        String printName=null;
        if(ad9!=null){
            print =ad9.getValue();
            printName =ad9.getUserName();
            vars.put(print, printName);
        }

        //安平物资管理主管
        AddDict ad10= addDictDao.findByLabel("安平物资管理主管", companyId,DEL_FLAG_NORMAL);
        if(ad10!=null){
            vars.put(ad10.getValue(), ad10.getUserName());
        }
        //安平物资管理主管
        AddDict ad11= addDictDao.findByLabel("安平医护部部长", companyId,DEL_FLAG_NORMAL);
        if(ad11!=null){
            vars.put(ad11.getValue(), ad11.getUserName());
        }
        AddDict ad12= addDictDao.findByLabel("安平财务部部长", companyId,DEL_FLAG_NORMAL);
        if(ad12!=null){
            vars.put(ad12.getValue(), ad12.getUserName());
        }
        AddDict ad13= addDictDao.findByLabel("安平执行院长", companyId,DEL_FLAG_NORMAL);
        if(ad13!=null){
            vars.put(ad13.getValue(), ad13.getUserName());
        }
        AddDict ad14= addDictDao.findByLabel("集团财务部", companyId,DEL_FLAG_NORMAL);
        if(ad14!=null){
            vars.put(ad14.getValue(), ad14.getUserName());
        }
        AddDict ad15= addDictDao.findByLabel("集团分管财务领导", companyId,DEL_FLAG_NORMAL);
        if(ad15!=null){
            vars.put(ad15.getValue(), ad15.getUserName());
        }
        AddDict ad16= addDictDao.findByLabel("集团管理层", companyId,DEL_FLAG_NORMAL);
        if(ad16!=null){
            vars.put(ad16.getValue(), ad16.getUserName());
        }
        AddDict ad17= addDictDao.findByLabel("康融总经理", companyId,DEL_FLAG_NORMAL);
        if(ad17!=null){
            vars.put(ad17.getValue(), ad17.getUserName());
        }
        AddDict ad18= addDictDao.findByLabel("康融董事长", companyId,DEL_FLAG_NORMAL);
        if(ad18!=null){
            vars.put(ad18.getValue(), ad18.getUserName());
        }
        AddDict ad19= addDictDao.findByLabel("归档", companyId,DEL_FLAG_NORMAL);
        if(ad19!=null){
            vars.put(ad19.getValue(), ad19.getUserName());
        }

        AddDict ad20= addDictDao.findByLabel("公司总经理", companyId,DEL_FLAG_NORMAL);
        if(ad20!=null){
            vars.put(ad20.getValue(), ad20.getUserName());
        }
        AddDict ad21= addDictDao.findByLabel("集团财务经理", companyId,DEL_FLAG_NORMAL);
        if(ad21!=null){
            vars.put(ad21.getValue(), ad21.getUserName());
        }
        AddDict ad22= addDictDao.findByLabel("集团分管财务领导", companyId,DEL_FLAG_NORMAL);
        if(ad22!=null){
            vars.put(ad22.getValue(), ad22.getUserName());
        }
        AddDict ad23= addDictDao.findByLabel("集团管理层负责人", companyId,DEL_FLAG_NORMAL);
        if(ad23!=null){
            vars.put(ad23.getValue(), ad23.getUserName());
        }
        AddDict ad24= addDictDao.findByLabel("行政人事部门", companyId,DEL_FLAG_NORMAL);
        if(ad24!=null){
            vars.put(ad24.getValue(), ad24.getUserName());
        }
        AddDict ad25= addDictDao.findByLabel("出纳付款", companyId,DEL_FLAG_NORMAL);
        if(ad25!=null){
            vars.put(ad25.getValue(), ad25.getUserName());
        }
        AddDict ad26= addDictDao.findByLabel("财务部经理", companyId,DEL_FLAG_NORMAL);
        if(ad26!=null){
            vars.put(ad26.getValue(), ad26.getUserName());
        }
        AddDict ad27= addDictDao.findByLabel("集团财务副经理", companyId,DEL_FLAG_NORMAL);
        if(ad27!=null){
            vars.put(ad27.getValue(), ad27.getUserName());
        }
        AddDict ad28= addDictDao.findByLabel("总经理的领导", companyId,DEL_FLAG_NORMAL);
        if(ad28!=null){
            vars.put(ad28.getValue(), ad28.getUserName());
        }

        AddDict ad29= addDictDao.findByLabel("集团投资发展部经理", companyId,DEL_FLAG_NORMAL);
        if(ad29!=null){
            vars.put(ad29.getValue(), ad29.getUserName());
        }

        //选择审批人
        if(flowData.getDatas().get("XZSPR")!=null){
            String XZSPR=flowData.getDatas().get("XZSPR").toString();
            if(StringUtils.isNotBlank(XZSPR)){
                User user11=new User();
                user11.setName(XZSPR);
                User user2=userDao.findByName(user11);
                String XZSPRLogimn="";
                if(user2!=null){
                    XZSPRLogimn=user2.getLoginName();
                }
                AddDict xzspr1 = addDictDao.findByLabel("审批人", "",DEL_FLAG_NORMAL);
                xzspr1.setUserName(XZSPRLogimn);
                String spr;
                String sprName;
                if(xzspr1!=null){
                    xzspr1.setUserName(XZSPRLogimn);
                    spr =xzspr1.getValue();
                    sprName =xzspr1.getUserName();
                    vars.put(spr, sprName);
                }
            }
        }


        //选择审批人
        if(flowData.getDatas().get("XZZNKS")!=null){
            String ZNKS=flowData.getDatas().get("XZZNKS").toString();
            if(StringUtils.isNotBlank(ZNKS)){
                User user11=new User();
                user11.setName(ZNKS);
                User user2=userDao.findByName(user11);
                String ZNKSLogimn="";
                if(user2!=null){
                    ZNKSLogimn=user2.getLoginName();
                }
                AddDict znks1 = addDictDao.findByLabel("职能科室", "",DEL_FLAG_NORMAL);
                znks1.setUserName(ZNKSLogimn);
                String znks;
                String znksName;
                if(znks1!=null){
                    znks1.setUserName(ZNKSLogimn);
                    znks =znks1.getValue();
                    znksName =znks1.getUserName();
                    vars.put(znks, znksName);
                }
            }
        }


        //选择审批人
        if(flowData.getDatas().get("XZZGBM")!=null){
            String ZGBM=flowData.getDatas().get("XZZGBM").toString();
            if(StringUtils.isNotBlank(ZGBM)){
                User user11=new User();
                user11.setName(ZGBM);
                User user2=userDao.findByName(user11);
                String ZGBMLogimn="";
                if(user2!=null){
                    ZGBMLogimn=user2.getLoginName();
                }
                AddDict zgbm1 = addDictDao.findByLabel("主管部门", "",DEL_FLAG_NORMAL);
                zgbm1.setUserName(ZGBMLogimn);
                String zgbm;
                String zgbmName;
                if(zgbm1!=null){
                    zgbm1.setUserName(ZGBMLogimn);
                    zgbm =zgbm1.getValue();
                    zgbmName =zgbm1.getUserName();
                    vars.put(zgbm, zgbmName);
                }
            }
        }


        AddDict sladwuz = addDictDao.findByLabel("物资管理科员", companyId,DEL_FLAG_NORMAL);
        String wzglky=null;
        String wzglkyName=null;
        if(sladwuz!=null){
            wzglky =sladwuz.getValue();
            wzglkyName =sladwuz.getUserName();
            vars.put(wzglky,wzglkyName );
        }

        //一病区
        AddDict bq1= addDictDao.findByLabel("一病区", companyId,DEL_FLAG_NORMAL);
        String ybq=null;
        String ybqName=null;
        if(bq1!=null){
            ybq =bq1.getValue();
            ybqName =bq1.getUserName();
            vars.put(ybq, ybqName);
        }


        //二病区
        AddDict bq2= addDictDao.findByLabel("二病区", companyId,DEL_FLAG_NORMAL);
        String ebq=null;
        String ebqName=null;
        if(bq2!=null){
            ebq =bq2.getValue();
            ebqName =bq2.getUserName();
            vars.put(ebq, ebqName);
        }



        //三病区
        AddDict bq3= addDictDao.findByLabel("三病区", companyId,DEL_FLAG_NORMAL);
        String sbq=null;
        String sbqName=null;
        if(bq3!=null){
            sbq =bq3.getValue();
            sbqName =bq3.getUserName();
            vars.put(sbq, sbqName);
        }



        //四病区
        AddDict bq4= addDictDao.findByLabel("四病区", companyId,DEL_FLAG_NORMAL);
        String sgbq=null;
        String sgbqName=null;
        if(bq4!=null){
            sgbq =bq4.getValue();
            sgbqName =bq4.getUserName();
            vars.put(sgbq, sgbqName);
        }


        //五病区
        AddDict bq5= addDictDao.findByLabel("五病区", companyId,DEL_FLAG_NORMAL);
        String wbq=null;
        String wbqName=null;
        if(bq5!=null){
            wbq =bq5.getValue();
            wbqName =bq5.getUserName();
            vars.put(wbq, wbqName);
        }


        AddDict slyy1= addDictDao.findByLabel("护理管理科员", companyId,DEL_FLAG_NORMAL);
        String hlglky=null;
        String hlglkyName=null;
        if(slyy1!=null){
            hlglky =slyy1.getValue();
            hlglkyName =slyy1.getUserName();
            vars.put(hlglky, hlglkyName);
        }



        //十一病区
        AddDict bq10= addDictDao.findByLabel("十一病区", companyId,DEL_FLAG_NORMAL);
        String sybq=null;
        String sybqName=null;
        if(bq10!=null){
            sybq =bq10.getValue();
            sybqName =bq10.getUserName();
            vars.put(sybq, sybqName);
        }



        //十二病区区
        AddDict bq11= addDictDao.findByLabel("十二病区", companyId,DEL_FLAG_NORMAL);
        String sebq=null;
        String sebqName=null;
        if(bq11!=null){
            sebq =bq11.getValue();
            sebqName =bq11.getUserName();
            vars.put(sebq, sebqName);
        }



        //十三病区
        AddDict bq12= addDictDao.findByLabel("十三病区", companyId,DEL_FLAG_NORMAL);
        String ssbq=null;
        String ssbqName=null;
        if(bq12!=null){
            ssbq =bq12.getValue();
            ssbqName =bq12.getUserName();
            vars.put(ssbq, ssbqName);
        }



        //十四病区
        AddDict bq13= addDictDao.findByLabel("十四病区", companyId,DEL_FLAG_NORMAL);
        String ssgbq=null;
        String ssgbqName=null;
        if(bq13!=null){
            ssgbq =bq13.getValue();
            ssgbqName =bq13.getUserName();
            vars.put(ssgbq, ssgbqName);
        }





        //急诊科
        AddDict bq16= addDictDao.findByLabel("急诊科", companyId,DEL_FLAG_NORMAL);
        String jzk=null;
        String jzkName=null;
        if(bq16!=null){
            jzk =bq16.getValue();
            jzkName =bq16.getUserName();
            vars.put(jzk, jzkName);
        }


        //手术室
        AddDict bq17= addDictDao.findByLabel("手术室", companyId,DEL_FLAG_NORMAL);
        String sss=null;
        String sssName=null;
        if(bq17!=null){
            sss =bq17.getValue();
            sssName =bq17.getUserName();
            vars.put(sss, sssName);
        }


        //供应室
        AddDict bq18= addDictDao.findByLabel("供应室", companyId,DEL_FLAG_NORMAL);
        String gys=null;
        String gysName=null;
        if(bq18!=null){
            gys =bq18.getValue();
            gysName =bq18.getUserName();
            vars.put(gys, gysName);
        }












        //呈批件中的呈送人
        if(flowData.getDatas().get("CSR")!=null){
            String CSR=flowData.getDatas().get("CSR").toString();
            if(StringUtils.isNotBlank(CSR)){
                User user11=new User();
                user11.setName(CSR);
                User user2=userDao.findByName(user11);
                String CSRLogimn="";
                if(user2!=null){
                    CSRLogimn=user2.getLoginName();
                }
                AddDict csr = addDictDao.findByLabel("呈批件", "",DEL_FLAG_NORMAL);
                csr.setUserName(CSRLogimn);
                String report;
                String reportName;
                if(csr!=null){
                    csr.setUserName(CSRLogimn);
                    report =csr.getValue();
                    reportName =csr.getUserName();
                    vars.put(report, reportName);
                }
            }
        }




        //删除id和标的医院的标识
        if (StringUtils.isNoneBlank(flowData.getId()) && StringUtils.isNoneBlank(flowData.getBZ())) {
            TargetHospital targetHospital = new TargetHospital();
            targetHospital.setId(flowData.getId());
            targetHospitalDao.delete(targetHospital);
            flowData.setId(null);
            flowData.setBZ(null);
        }


        if(StringUtils.isNoneBlank(flowData.getId()) && StringUtils.isNoneBlank(flowData.getSFCC())){
            if(flowData.getTableName()!="TRAVEL_APPLICATION"){
                TravelApplication travelApplication=travelApplicationDao.get(flowData.getId());
                if(travelApplication!=null){
                    travelApplication.setSfcc(null);
                    int i=travelApplicationDao.update(travelApplication);
                    if(i>0 && travelApplication!=null){
                        flowData.setId(null);
                    }
                }
            }
        }

        // 申请发起
        if (StringUtils.isBlank(flowData.getId())) {
            flowData.preInsert();
            String name = insertTable(flowData);
            if (StringUtils.isNotEmpty(name)) {
                User u = new User();
                u.setName(name.replace("'", ""));
                User user1 = userDao.findByName(u);
                // 启动流程

                return actTaskService.startProcess(flowData.getFlowFlag(), flowData.getTableName(), flowData.getId(), "自定义流程", vars, user1.getLoginName());
            } else {
                return actTaskService.startProcess(flowData.getFlowFlag(), flowData.getTableName(), flowData.getId(), "自定义流程", vars, "");
            }

        }
        // 重新编辑申请
        else {
            flowData.preUpdate();
            updateTable(flowData);
            if (flowData.getAct().getComment() == null) {
                flowData.getAct().setComment("");
            }
            if ((flowData.getAct().getTaskDefKey()).startsWith("edit")) {
                String userId = UserUtils.getUser().getLoginName();//ObjectUtils.toString(UserUtils.getUser().getId());
                actTaskService.claim(flowData.getAct().getTaskId(), userId);
                flowData.getAct().setComment(("yes".equals(flowData.getAct().getFlag()) ? "[编辑] " : "[驳回] ") + flowData.getAct().getComment());
                OaPersonDefineTable defineTable1 = oaPersonDefineTableDao.findByTableName(flowData.getTableName(), null);
                List<OaPersonDefineTableColumn> columns = oaPersonDefineTableColumnDao.findColumnListByTableId(defineTable1.getId());
//                param.setIsAudit("1");
//                List<OaPersonDefineTableColumn> columns = oaPersonDefineTableColumnDao.findList(param);
                for (OaPersonDefineTableColumn column : columns) {
                    if (flowData.getAct().getTaskDefKey().equals(column.getAuditPost())) {
                        String sql = "update " + flowData.getTableName() + " set "
                                + column.getColumnName() + "='" + flowData.getAct().getComment()
                                + "' where id='" + flowData.getId() + "'";
                        oaPersonDefineTableDao.executeSql(sql);
                        break;
                    }
                }

                Map<String, Object> var = Maps.newHashMap();
                var.put("pass", "yes".equals(flowData.getAct().getFlag()) ? "1" : "0");

                actTaskService.complete(flowData.getAct().getTaskId(), flowData.getAct().getProcInsId(), flowData.getAct().getComment(), var);
            } else {
                flowData.getAct().setComment(("yes".equals(flowData.getAct().getFlag()) ? "[重申] " : "[销毁] ") + flowData.getAct().getComment());

                // 完成流程任务
                vars.put("pass", "yes".equals(flowData.getAct().getFlag()) ? "1" : "0");
                actTaskService.complete(flowData.getAct().getTaskId(), flowData.getAct().getProcInsId(), flowData.getAct().getComment(), "自定义流程", vars);
                if ("yes".equals(flowData.getAct().getFlag())) {
                    OaPersonDefineTable table = oaPersonDefineTableDao.findByTableName(flowData.getTableName(), null);
                    OaPersonDefineTableColumn param = new OaPersonDefineTableColumn(table);
                    param.setIsAudit("1");
                    List<OaPersonDefineTableColumn> columns = oaPersonDefineTableColumnDao.findList(param);
                    StringBuilder sb = new StringBuilder("update " + flowData.getTableName() + " set ");
                    String split = "";
                    for (OaPersonDefineTableColumn column : columns) {
                        sb.append(split + column.getColumnName() + "=''");
                        split = ",";
                    }
                    sb.append(" where id='" + flowData.getId() + "'");
                    oaPersonDefineTableDao.executeSql(sb.toString());
                }
            }
        }
        return "";
    }

    /**
     * 审核审批保存
     *
     * @param flowData
     */
    @Transactional(readOnly = false)
    public String  auditSave(FlowData flowData) {
        User user = UserUtils.getUser();
        // 设置意见
        if(!(flowData.getAct().getTaskDefKey().startsWith("apply_cs"))){
            flowData.getAct().setComment(("yes".equals(flowData.getAct().getFlag()) ? "[同意]" : "[驳回] ") + flowData.getAct().getComment());
        }
        flowData.preUpdate();
        // 对不同环节的业务逻辑进行操作
        String taskDefKey = flowData.getAct().getTaskDefKey();
        // 审核环节
        if (taskDefKey.startsWith("audit") || (taskDefKey).startsWith("apply_execute") || "apply_end".equals(taskDefKey) || taskDefKey.startsWith("apply_cs")) {
            OaPersonDefineTable table = oaPersonDefineTableDao.findByTableName(flowData.getTableName(), null);
            OaPersonDefineTableColumn param = new OaPersonDefineTableColumn(table);
            param.setIsAudit("1");
            List<OaPersonDefineTableColumn> columns = oaPersonDefineTableColumnDao.findList(param);
            for (OaPersonDefineTableColumn column : columns) {
                if (taskDefKey.equals(column.getAuditPost())) {
                    String sql = "update " + flowData.getTableName() + " set "
                            + column.getColumnName() + "='" + flowData.getAct().getComment()
                            + "' where id='" + flowData.getId() + "'";
                    oaPersonDefineTableDao.executeSql(sql);
                    break;
                }
            }
        }
        // 未知环节，直接返回
        else {
            return "";
        }
        // 提交流程任务
        List<String> assigneeListBefore=new ArrayList<String>(); //分配集合中的任务的人员
        String[] userLoginNames = null;

        Map<String, Object> vars = Maps.newHashMap();
        vars.put("pass", "yes".equals(flowData.getAct().getFlag()) ? "1" : "0");
        //抄送任务
        if(flowData.getAct().getCSLoginNames() !=null && StringUtils.isNotBlank(flowData.getAct().getCSLoginNames())){
            userLoginNames = flowData.getAct().getCSLoginNames().split(",");
            Collections.addAll(assigneeListBefore,userLoginNames);
        }

        //驳回抄送
        String SQR = null;
        if(!StringUtils.equalsIgnoreCase(flowData.getAct().getFlag(),"yes")){

            String sql="SELECT * FROM act_hi_identitylink WHERE PROC_INST_ID_='"+flowData.getAct().getProcInsId()+"' and  type_='starter'";
            List<Map<String,Object>> sqls = oaPersonDefineTableDao.getFlowInfo(sql);
            if(sqls != null && sqls.size()>0){
                Map<String,Object> map = sqls.get(0);
                String s=null;
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    if(StringUtils.equalsIgnoreCase("USER_ID_",entry.getKey())){
                        SQR = entry.getValue().toString();
                        break;
                    }
                }
            }
            List<HistoricActivityInstance> hisActInstList = historyService.createHistoricActivityInstanceQuery().processInstanceId(flowData.getAct().getProcInsId()).activityType("userTask").list();
            if(hisActInstList !=null && hisActInstList.size()>0){
                for(HistoricActivityInstance historicActivityInstance : hisActInstList){
                    if(!(StringUtils.equalsIgnoreCase(historicActivityInstance.getActivityId(),flowData.getAct().getTaskDefKey())) && !(historicActivityInstance.getActivityName().startsWith("抄送任务"))
                            && !(StringUtils.equalsIgnoreCase("modify",historicActivityInstance.getActivityId()))){
                            assigneeListBefore.add(historicActivityInstance.getAssignee());
                    }
                }
            }
        }
        //去除list中的重复数据
        Set set = new  HashSet();
        List assigneeList = new  ArrayList();
        for (String cd:assigneeListBefore) {
            if(set.add(cd)){
                assigneeList.add(cd);
            }
        }

        if(assigneeList.size() == 1 && StringUtils.equalsIgnoreCase(assigneeList.get(0).toString(),SQR)){
              assigneeList = new ArrayList();
        }else{
            vars.put("assigneeList",assigneeList);
        }
        actTaskService.complete(flowData.getAct().getTaskId(), flowData.getAct().getProcInsId(), flowData.getAct().getComment(), vars);
        return flowData.getAct().getFlag();
    }


    /**
     * 数据类型适配-根据表单配置的字段类型将前台传递的值将map-value转换成相应的类型
     *
     * @param columns
     * @param data    数据
     */
    private Map<String, Object> dataAdapter(List<OaPersonDefineTableColumn> columns, Map<String, Object> data) {
        //step.2 迭代将要持久化的数据
        for (OaPersonDefineTableColumn column : columns) {
            //根据表单配置的字段名 获取 前台数据
            String columnName = column.getColumnName();
            Object beforeV = data.get(columnName);
            //如果值不为空
            if (OConvertUtils.isNotEmpty(beforeV)) {
                //获取字段配置-字段类型
                String type = column.getColumnType();
                //根据类型进行值的适配
                data.put(columnName, handleSqlValue(beforeV, type));
            }
        }
        return data;
    }

    private String handleSqlValue(Object value, String type) {
        if (value == null) return null;
        Object newV = "";
        if ("date".equalsIgnoreCase(type) || "datetime".equalsIgnoreCase(type)) {
            newV = "date_format('" + String.valueOf(value) + "','%Y-%m-%d')";
        } else if ("number".equalsIgnoreCase(type) || "NUMERIC".equalsIgnoreCase(type)) {
            newV = new Double(0);
            try {
                String value1 = String.valueOf(value);
                if (value1.contains(",")) {
                    value1 = String.valueOf(value).replace(",", "");
                }
                newV = Double.parseDouble(value1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("varchar".equalsIgnoreCase(type) || "varchar2".equalsIgnoreCase(type)) {
            newV = "'" + String.valueOf(value) + "'";
        } else {
            return null;
        }
        return String.valueOf(newV);
    }

    //判断key是否为表配置的属性
    private boolean isContainsFieled(List<OaPersonDefineTableColumn> columns, String fieledName) {
        for (int i = 0; i < columns.size(); i++) {
            if (columns.get(i).getColumnName().equals(fieledName.toUpperCase())) {
                return true;
            }
        }
        return false;
    }

    private String getSelectSql(Map<String, String> paramMap) {
        String tableName = paramMap.get("tableName");
        String procInsId = paramMap.get("procInsId");
        String id = paramMap.get("id");
        String createBy = paramMap.get("createBy");
        String procDefId = paramMap.get("procDefId");
        String name=paramMap.get("name");
        String dept=paramMap.get("dept");
        String numberDay=paramMap.get("numberDay");
        String fh=paramMap.get("fh");
        String arriveDay=paramMap.get("arriveDay");
        String startDate=paramMap.get("startDate");
        String endDate=paramMap.get("endDate");
        StringBuilder sql = null;
        OaPersonDefineTable defineTable = oaPersonDefineTableDao.findByTableName(tableName, null);
        if (defineTable != null) {
            List<OaPersonDefineTableColumn> columns = oaPersonDefineTableColumnDao.findColumnListByTableId(defineTable.getId());
            if (columns != null && columns.size() > 0) {
                sql = new StringBuilder("select id,proc_ins_id procInsId,create_by");
                for (OaPersonDefineTableColumn column : columns) {
                    if ("DATE".equals(column.getColumnType().toUpperCase())) {
                        sql.append(",replace(date_format(" + column.getColumnName() + ",'%Y-%m-%d'),' 00:00:00','') " + column.getColumnName());
                    } else {
                        sql.append("," + column.getColumnName());
                    }
                }
                sql.append(" from " + tableName + " where del_flag = '0'");
                if (StringUtils.isNotBlank(id)) {
                    sql.append(" and id='" + id + "' ");
                }
                for (OaPersonDefineTableColumn column : columns) {
                    if(StringUtils.equalsIgnoreCase(column.getColumnComment(),"申请人") || StringUtils.equalsIgnoreCase(column.getColumnComment(),"出差人") || StringUtils.equalsIgnoreCase(column.getColumnComment(),"姓名")
                            || StringUtils.equalsIgnoreCase(column.getColumnComment(),"被调薪人")){
                        if(StringUtils.isNotBlank(name)){
                            sql.append(" and "+column.getColumnName()+" like '%" + name + "%' ");
                        }
                    }

                    if(column.getColumnComment().indexOf("天数")!=-1){
                        if(StringUtils.isNotBlank(numberDay)&& StringUtils.isNotBlank(fh)){
                            if(StringUtils.equalsIgnoreCase(fh,"1")){
                                sql.append(" and "+column.getColumnName()+" >=  '" + numberDay + "' ");
                            }else if(StringUtils.equalsIgnoreCase(fh,"2")){
                                sql.append(" and "+column.getColumnName()+"  <=  '" + numberDay + "' ");
                            }else if(StringUtils.isNotBlank(arriveDay) && StringUtils.equalsIgnoreCase(fh,"3")){
                                sql.append(" and "+column.getColumnName()+" >= '" + numberDay + "' and "+column.getColumnName() +"<="+arriveDay);
                            }
                        }

                    }

                    if(column.getColumnComment().indexOf("开始时间")!=-1 || column.getColumnComment().indexOf("开始日期")!=-1 ) {
                        if(StringUtils.isNotBlank(startDate)){
                            sql.append(" and "+column.getColumnName()+" >= '" + startDate + "' ");
                        }
                    }

                    if(column.getColumnComment().indexOf("结束时间")!=-1 || column.getColumnComment().indexOf("结束日期")!=-1 ) {
                        if(StringUtils.isNotBlank(endDate)) {
                            sql.append(" and " + column.getColumnName() + " <= '" + endDate + "' ");
                        }
                    }
                }
                if (StringUtils.isNotBlank(dept)) {
                    sql.append(" and BM='" + dept + "' ");
                }
                if (StringUtils.isNotBlank(procInsId)) {
                    sql.append(" and proc_ins_id='" + procInsId + "' ");
                }
                if (StringUtils.isNotBlank(createBy)) {
                    sql.append(" and create_by='" + createBy + "' ");
                }
                if (StringUtils.isNotBlank(procDefId)) {
                    sql.append(" and proc_def_id='" + procDefId + "' ");
                }
                sql.append("order by CREATE_DATE desc");
            }
        }
        if (sql != null) return sql.toString();
        return null;
    }

    private Map<String, Object> handlerVar(String tableName, Map<String, Object> datas) {
        Map<String, Object> vars = Maps.newHashMap();
        if (StringUtils.isNotBlank(tableName) && datas != null && datas.keySet().size() < 65) {
            List<OaPersonDefineTableColumn> columns = oaPersonDefineTableColumnDao.getColumns(tableName);
            if (columns != null && columns.size() > 0) {
                for (OaPersonDefineTableColumn column : columns) {
                    vars.put(column.getColumnName(), datas.get(column.getColumnName()));
                }
            }
        } else {
            List<OaPersonDefineTableColumn> columns = oaPersonDefineTableColumnDao.getColumns(tableName);
            if (columns != null && columns.size() > 0) {
                for (OaPersonDefineTableColumn column : columns) {
                    if (column.getIsProcess() != null) {
                        vars.put(column.getColumnName(), datas.get(column.getColumnName()));
                    }
                }
            }
        }
        return vars;
    }
}
